//
//  OAuthViewController.swift
//  DSWeiBo
//
//  Created by H on 16/5/24.
//  Copyright © 2016年 Mr.Lin. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    let WB_Client_ID = "2783946009"
    let WB_App_Secret = "1a0f3192e21680a71e099b264550c61a"
    let WB_REDIRECT_URI = "http://www.520it.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {

        navigationItem.title = "大寒微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title:"关闭",style: .Plain,target: self,action: #selector(OAuthViewController.close))
        //获取未授权的RequestToken
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL:url!)
        webView.loadRequest(request)
    }
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView:UIWebView = {
        let wv = UIWebView()
        wv.delegate = self
        return wv 
    }()
}

extension OAuthViewController:UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1。判断是否是授权回调页面 如果不是就继续加载
        if !request.URL!.absoluteString.hasPrefix(WB_REDIRECT_URI) {
           return true
        }
        //2.判断是是否授全成功
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr){
            //授权成功
          let code = request.URL?.query!.substringFromIndex(codeStr.endIndex)
            //2. 利用已经授权的requestToken换取AccessToken
            loadAccessToken(code!)
        
        
        }else{
            //取消授权
            close()
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        //提示用户正在加载
        SVProgressHUD.showInfoWithStatus("正在加载")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    private func loadAccessToken(code:String){
        //定义路径 
        let path = "oauth2/access_token"
        //请求参数
        let params = ["client_id":WB_Client_ID,"client_secret":WB_App_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_REDIRECT_URI]
        //发起网络请求
        NetworkTool.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) -> Void  in
            //2.00LU1pkFzWJ6CD0ef7035d662IrOnD
                print(JSON)
            let account = Useraccount(dict:JSON as! [String:AnyObject])
            
            //2.1 获取用户信息
            account.loadUserInfo({ (account, error) in
                if account != nil {
                    account!.saveAccount()
                }
                print(account)

            })
            
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
}
